﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.Threading;
using System.Configuration;

namespace TestNamedPipeLogReaderForConsole
{
    class ProgramPipeTest
    {
        private byte m_maxConnectionInstance = 0;
        public void Start(byte maxConnectionInstance)
        {
            m_maxConnectionInstance = maxConnectionInstance;
            for (int i = 0; i < maxConnectionInstance; i++)
            {
                Thread newThread = new Thread(ThreadStartServer);
                newThread.Start();
            }
        }
        private void ThreadStartServer()
        {
            string pipeName = ConfigurationManager.AppSettings["PipeName"];
            // Create a name pipe
            using (NamedPipeServerStream pipeStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, m_maxConnectionInstance))
            {
                Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());
                pipeStream.WaitForConnection();
                Console.WriteLine("[Server] Pipe connection established");
                while (true)
                {
                    // Wait for a connection       
                    try
                    {
                        
                        byte[] buffer = new byte[1024];
                        int readedByte = pipeStream.Read(buffer, 0, buffer.Length);
                        if (readedByte == 0)
                        {
                            throw new System.IO.IOException();
                        }

                        string str = Encoding.Unicode.GetString(buffer, 0, readedByte);
                        Console.WriteLine("{0}: {1}", DateTime.Now, str);
                    }
                    catch (System.Exception ex)
                    {
                        pipeStream.Disconnect();
                        pipeStream.Close();
                        ThreadStartServer();
                    }                   
                    
                }
            }
        }      

    }
    class Program
    {
        static void Main(string[] args)
        {
            ProgramPipeTest Server = new ProgramPipeTest();
            byte maxConnectionInstance = Convert.ToByte(ConfigurationManager.AppSettings["MaxConnectionInstance"]);
            
            Server.Start(maxConnectionInstance);
        }
    }
}
